from django.db import transaction
from rest_framework import permissions
from rest_framework.exceptions import ValidationError
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken
from utils import response_ok, response_error
from utils.custom_modelviewset import CustomModelViewSet
from apps.member.models import Member
from apps.system.models import SystemLog
from utils.exceptions import CustomError
from .serializers import UserJWTSerializer, AccountSerializer, MemberSerializer
from .models import User
from .filters import AccountFilter, MemberFilter


# Create your views here.
class AdminLoginView(ObtainJSONWebToken):
    serializer_class = UserJWTSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)

            if ser.is_valid(raise_exception=True):
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.get_full_details()['non_field_errors'][0]['message'])


class AccountViewSet(CustomModelViewSet):
    '''后台用户CRUD操作'''
    queryset = User.objects.filter(is_staff=True)
    serializer_class = AccountSerializer
    permission_classes = [permissions.IsAdminUser]

    def filter_queryset(self, queryset):
        print(self.request.GET)
        f = AccountFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                username = request.data['mobile']
                password = request.data['password']
                nickname = request.data['nickname']
                user = User.objects.create_superuser(username=username, password=password, nickname=nickname)
                SystemLog.objects.add_log(request.user, SystemLog.INSERT, u'创建管理员，username=%s' % user.username)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()


class MemberViewSet(CustomModelViewSet):
    '''后台会员CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = Member.objects.filter()
    serializer_class = MemberSerializer

    def filter_queryset(self, queryset):
        f = MemberFilter(self.request.GET, queryset=self.queryset)
        return f.qs


class DictView(APIView):
    permission_classes = [permissions.IsAdminUser]

    # 返回产品的字典参数
    def get(self, request):
        ret = {
            'identity': Member.IDENTITY_JSON
        }
        return response_ok(ret)


class MenuView(APIView):
    permission_classes = [permissions.IsAdminUser]

    def post(self, request, *args, **kwargs):
        menu = [
            {
                'name': '仪表盘',
                'icon': 'dashboard',
                'path': '/dashboard',
            },
            {
                'name': '用户管理',
                'icon': 'setting',
                'path': '/member',
                'children': [{
                    'name': '用户管理',
                    'path': '/member',
                }, ]
            },
            {
                'name': '文章管理',
                'icon': 'setting',
                'path': '/article',
                'children': [{
                    'name': '文章管理',
                    'path': '/article',
                }, ]
            },
            {
                'name': '案例管理',
                'icon': 'setting',
                'path': '/house',
                'children': [{
                    'name': '装修案例',
                    'path': '/house/:room?',
                }]
            },
            {
                'name': '装修百科',
                'icon': 'setting',
                'path': '/adorn_pedia',
                'children': [{
                    'name': '装修百科',
                    'path': '/adorn_pedia',
                }]
            },
            {
                'name': '装修流程',
                'icon': 'setting',
                'path': '/adorn_process',
                'children': [{
                    'name': '装修流程',
                    'path': '/adorn_process',
                }]
            },
            {
                'name': '服务管理',
                'icon': 'setting',
                'path': '/service',
                'children': [{
                    'name': '服务管理',
                    'path': '/adorn',
                }, {
                    'name': '预约服务管理',
                    'path': '/order',
                }]
            },
            {
                'name': '产品管理',
                'icon': 'setting',
                'path': '/product',
                'children': [{
                    'name': '产品管理',
                    'path': '/product/:parameter?',
                }]
            },
            {
                'name': '工人管理',
                'icon': 'setting',
                'path': '/worker',
                'children': [{
                    'name': '工人管理',
                    'path': '/worker',
                }, ]
            },
            {
                'name': '系统管理',
                'icon': 'setting',
                'path': '/system',
                'children': [{
                    'name': '系统选项',
                    'path': '/system/option',
                }, ]
            }, {
                'name': '组件',
                'icon': 'DesktopOutlined',
                'path': '/component',
                'children': [
                    {
                        'name': '工具条',
                        'path': '/toolbar',
                    },
                    {
                        'name': 'BaseComponent',
                        'path': '/baseComponent',
                    },
                    {
                        'name': 'Columns',
                        'path': '/column',
                    },
                    {
                        'name': '搜索条',
                        'path': '/searchBar',
                    },
                    {
                        'name': '数据表格',
                        'path': '/datatable',
                    },
                    {
                        'name': '表单',
                        'path': '/form',
                    },
                    {
                        'name': '穿梭树',
                        'path': '/transferTree',
                    },
                    {
                        'name': '图表',
                        'path': '/charts',
                        'children': [
                            {
                                'name': 'ECharts',
                                'path': '/charts/ec',
                            },
                            {
                                'name': 'G2',
                                'path': '/charts/g2',
                            },
                        ]
                    },
                    {
                        'name': '打印',
                        'path': '/print',
                    },
                    {
                        'name': 'Banner 管理',
                        'path': '/banner',
                    },
                ],
            },
            {
                'name': 'UI元素',
                'icon': 'ShareAltOutlined',
                'path': '/ui',
                'children': [
                    {
                        'name': '按钮',
                        'path': '/button',
                    },
                    {
                        'name': '图片',
                        'path': '/image',
                    },
                    {
                        'name': '消息',
                        'path': '/alerts',
                    },
                    {
                        'name': '动画',
                        'path': '/animations',
                    },
                    {
                        'name': '图标',
                        'path': '/icons',
                    },
                    {
                        'name': '富文本',
                        'path': '/editor',
                    },
                    {
                        'name': '模态窗',
                        'path': '/modal',
                    },
                    {
                        'name': '遮罩',
                        'path': '/mask',
                    },
                ],
            },
            {
                'name': '页面',
                'icon': 'BookOutlined',
                'path': '/page',
                'children': [
                    {
                        'name': '登录页',
                        'path': '/sign/login',
                    },
                    {
                        'name': '注册页',
                        'path': '/sign/register',
                    },
                    {
                        'name': '锁屏',
                        'path': '/lock',
                    },
                    {
                        'name': '画廊',
                        'path': '/gallery',
                    },
                    {
                        'name': '空白页',
                        'path': '/blank',
                    },
                    {
                        'name': '结果页',
                        'path': '/result',
                    },
                    {
                        'name': 'Coming Soon',
                        'path': '/coming',
                    },
                    {
                        'name': '403',
                        'path': '/403',
                    },
                    {
                        'name': '404',
                        'path': '/404',
                    },
                    {
                        'name': '500',
                        'path': '/500',
                    },
                    {
                        'name': '多级路由',
                        'path': '/level-route/:sub?',
                    },
                ],
            },
            {
                'name': '通用场景',
                'icon': 'BulbOutlined',
                'path': '/business',
                'children': [
                    {
                        'name': 'CRUD',
                        'path': '/crud/:detail?',
                    }
                ],
            }
        ]
        return response_ok(menu)
